// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "stateseditormodel.h"
#include "stateseditorview.h"

#include <QDebug>

#include <nodelistproperty.h>
#include <modelnode.h>
#include <bindingproperty.h>
#include <variantproperty.h>
#include <rewriterview.h>

#include <coreplugin/icore.h>
#include <coreplugin/messagebox.h>

#include <QWidget>

enum {
    debug = false
};


namespace QmlDesigner {

StatesEditorModel::StatesEditorModel(StatesEditorView *view)
    : QAbstractListModel(view),
      m_statesEditorView(view),
      m_updateCounter(0)
{
}

int StatesEditorModel::count() const
{
    return rowCount();
}

QModelIndex StatesEditorModel::index(int row, int column, const QModelIndex &parent) const
{
    if (m_statesEditorView.isNull())
        return {};

    int internalNodeId = 0;
    if (row > 0 && row < rowCount() - 1) // first and last rows are base state, add state
        internalNodeId = m_statesEditorView->acitveStatesGroupNode().nodeListProperty("states").at(row - 1).internalId();

    return hasIndex(row, column, parent) ? createIndex(row, column,  internalNodeId) : QModelIndex();
}

int StatesEditorModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid() || m_statesEditorView.isNull() || !m_statesEditorView->model())
        return 0;

    if (!m_statesEditorView->acitveStatesGroupNode().hasNodeListProperty("states"))
        return 2; // base state + add new state

    return m_statesEditorView->acitveStatesGroupNode().nodeListProperty("states").count() + 2; // 2 = base state + add new state
}

void StatesEditorModel::reset()
{
    QAbstractListModel::beginResetModel();
    QAbstractListModel::endResetModel();
}

QVariant StatesEditorModel::data(const QModelIndex &index, int role) const
{
    if (index.parent().isValid() || index.column() != 0 || m_statesEditorView.isNull() || !m_statesEditorView->hasModelNodeForInternalId(index.internalId()))
        return QVariant();

    ModelNode stateNode;

    if (index.internalId() > 0)
        stateNode = m_statesEditorView->modelNodeForInternalId(index.internalId());

    switch (role) {
    case StateNameRole: {
        if (index.row() == 0) {
            return tr("base state", "Implicit default state");
        } else {
            if (stateNode.hasVariantProperty("name"))
                return stateNode.variantProperty("name").value();
            else
                return QVariant();
        }
    }

    case StateImageSourceRole: {
        static int randomNumber = 0;
        randomNumber++;
        if (index.row() == 0)
            return QString("image://qmldesigner_stateseditor/baseState-%1").arg(randomNumber);
        else
            return QString("image://qmldesigner_stateseditor/%1-%2").arg(index.internalId()).arg(randomNumber);
    }

    case InternalNodeId:
        return index.internalId();

    case HasWhenCondition:
        return stateNode.hasProperty("when");

    case WhenConditionString:
        return stateNode.bindingProperty("when").expression();

    case IsDefault: {
        return QmlModelState(stateNode).isDefault();
    }

    case ModelHasDefaultState:
        return hasDefaultState();

    case StateType:
        return index.row() == rowCount() - 1 ? "add" : "state";
    }

    return QVariant();
}

QHash<int, QByteArray> StatesEditorModel::roleNames() const
{
    static QHash<int, QByteArray> roleNames {
        {StateNameRole, "stateName"},
        {StateImageSourceRole, "stateImageSource"},
        {InternalNodeId, "internalNodeId"},
        {HasWhenCondition, "hasWhenCondition"},
        {WhenConditionString, "whenConditionString"},
        {IsDefault, "isDefault"},
        {ModelHasDefaultState, "modelHasDefaultState"},
        {StateType, "type"}
    };
    return roleNames;
}

void StatesEditorModel::insertState(int stateIndex)
{
    if (stateIndex >= 0) {
        const int updateIndex = stateIndex + 1;
        beginInsertRows(QModelIndex(), updateIndex, updateIndex);
        endInsertRows();

        emit dataChanged(index(updateIndex, 0), index(updateIndex, 0));
    }
}

void StatesEditorModel::updateState(int beginIndex, int endIndex)
{
    if (beginIndex >= 0 && endIndex >= 0)
        emit dataChanged(index(beginIndex, 0), index(endIndex, 0));
}

void StatesEditorModel::removeState(int stateIndex)
{
    if (stateIndex >= 0) {
        beginRemoveRows(QModelIndex(), 0, stateIndex);
        endRemoveRows();

        beginResetModel();
        endResetModel();
    }
}

void StatesEditorModel::renameState(int internalNodeId, const QString &newName)
{
    if (newName == m_statesEditorView->currentStateName())
        return;

    if (newName.isEmpty() ||! m_statesEditorView->validStateName(newName)) {
        QTimer::singleShot(0, [newName]{
            Core::AsynchronousMessageBox::warning(
                        tr("Invalid State Name"),
                        newName.isEmpty() ?
                            tr("The empty string as a name is reserved for the base state.") :
                            tr("Name already used in another state."));
        });
        reset();
    } else {
        m_statesEditorView->renameState(internalNodeId, newName);
    }

}

void StatesEditorModel::setWhenCondition(int internalNodeId, const QString &condition)
{
    m_statesEditorView->setWhenCondition(internalNodeId, condition);
}

void StatesEditorModel::resetWhenCondition(int internalNodeId)
{
    m_statesEditorView->resetWhenCondition(internalNodeId);
}

QStringList StatesEditorModel::autoComplete(const QString &text, int pos, bool explicitComplete)
{
    Model *model = m_statesEditorView->model();
    if (model && model->rewriterView())
        return model->rewriterView()->autoComplete(text, pos, explicitComplete);

    return QStringList();
}

QVariant StatesEditorModel::stateModelNode()
{
    return QVariant::fromValue(m_statesEditorView->currentStateNode());
}

void StatesEditorModel::setStateAsDefault(int internalNodeId)
{
    m_statesEditorView->setStateAsDefault(internalNodeId);
}

void StatesEditorModel::resetDefaultState()
{
    m_statesEditorView->resetDefaultState();
}

bool StatesEditorModel::hasDefaultState() const
{
    return m_statesEditorView->hasDefaultState();
}

void StatesEditorModel::setAnnotation(int internalNodeId)
{
    m_statesEditorView->setAnnotation(internalNodeId);
}

void StatesEditorModel::removeAnnotation(int internalNodeId)
{
    m_statesEditorView->removeAnnotation(internalNodeId);
}

bool StatesEditorModel::hasAnnotation(int internalNodeId) const
{
    return m_statesEditorView->hasAnnotation(internalNodeId);
}

} // namespace QmlDesigner
